import time

import logging
#创建日志对象
logger=logging.getLogger("django")
#配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    filename="blog.log",
    filemode="a"
)
class LoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        #取开始时间
        start_time = time.time()
        print("============访问了中间件 logging middleware===========")
        response = self.get_response(request)
        end_time = time.time()
        total=end_time-start_time
        print("total:",total)
        #写日志格式：Path: /admin/ | Method: GET | IP: 127.0.0.1 | Duration: 0.45s
        log_line=f'path: {request.path} | method: {request.method} | ip: {request.META["REMOTE_ADDR"]} | duration: {total}'
        #写入日志文件
        logging.info(log_line)
        print(log_line)
        return response